<template>
    <div>
        <el-row :gutter="20" class="form-line">
            <el-col :span="3" class="form-label">
                所属服务
            </el-col>
            <el-col :span="3">
                <el-select size="small"
                           v-model="roleObj.serviceCode"
                           @change="changeService"
                           filterable>
                    <el-option
                            v-for="item in roleObj.serviceList"
                            :key="item.serviceCode"
                            :label="item.serviceName"
                            :value="item.serviceCode">
                    </el-option>
                </el-select>
            </el-col>
            <el-col :span="3" class="form-label">
                角色名称
            </el-col>
            <el-col :span="3">
                <el-input v-model="roleObj.roleName" size="small"></el-input>
            </el-col>
            <el-col :span="6" :offset="6">
                <el-button type="primary" size="small" @click="selectRoleList">查询</el-button>
                <el-button type="primary" size="small" @click="roleObj.dialogFormVisible = true">新增</el-button>
            </el-col>
        </el-row>

        <el-table
                :data="roleObj.roleListShow"
                min-width="100%">
            <el-table-column
                    prop="roleName"
                    label="角色名称"
                    min-width="25%">
            </el-table-column>
            <el-table-column
                    prop="descr"
                    label="角色描述"
                    min-width="35%">
            </el-table-column>
            <el-table-column
                    prop="status"
                    label="状态"
                    min-width="20%">
                <template slot-scope="scope">
                    <el-switch
                            :active-value="1"
                            :inactive-value="0"
                            v-model="scope.row.status"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            @change="statusMenu(scope.row.id,scope.row.status)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column
                    label="操作" min-width="20%">
                <template slot-scope="scope">
                    <el-popover
                            placement="top"
                            width="160"
                            v-model="scope.row.popover">
                        <p>确认删除？</p>
                        <div style="text-align: right; margin: 0">
                            <el-button size="mini" type="text" @click="scope.row.popover = false">取消</el-button>
                            <el-button type="primary" size="mini" @click="deleteRole(scope.row.id)">确定</el-button>
                        </div>
                        <el-button class="delete-margin" size="small" type="text" slot="reference">删除</el-button>
                    </el-popover>
                    <el-button type="text" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
                    <el-button type="text" size="small" @click="openUserDialog(scope.row)">授权</el-button>
                </template>
            </el-table-column>
        </el-table>


        <el-pagination
                class="se-pagination"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page.sync="roleObj.currentPage"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="roleObj.currentSize"
                :hide-on-single-page="false"
                layout="total, sizes, prev, pager, next"
                :total="roleObj.total">
        </el-pagination>

        <el-dialog title="新增角色" :visible.sync="roleObj.dialogFormVisible" width="30%">
        <el-form  label-width="80px" :model="roleObj.roleDialog" :rules="roleRules" ref="addRoleForm">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="roleObj.roleDialog.roleName" size="small"></el-input>
            </el-form-item>
            <el-form-item label="角色描述">
                <el-input type="textarea" v-model="roleObj.roleDialog.descr" size="small"></el-input>
            </el-form-item>
            <el-form-item label="启用">
                <el-switch
                        v-model="roleObj.roleDialog.status"
                        active-color="#13ce66"
                        inactive-color="#ff4949">
                </el-switch>
            </el-form-item>
            <el-form-item label="菜单权限">
                <el-tree
                        check-strictly
                        @check-change="handleInsertCheckChange"
                        ref="insertTree"
                        node-key="id"
                        :data="roleObj.menuTree"
                        :props="roleObj.props"
                        show-checkbox>
                </el-tree>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="clearRoleDialog">取 消</el-button>
            <el-button type="primary" @click="insertRole('addRoleForm')">确 定</el-button>
        </div>
        </el-dialog>

        <el-dialog title="编辑角色" :visible.sync="roleObj.dialogEditRoleVisible" width="30%">
            <el-form  label-width="80px" :model="roleObj.roleDialog" :rules="roleRules" ref="editRoleForm">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="roleObj.roleDialog.roleName" size="small"></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input type="textarea" v-model="roleObj.roleDialog.descr" size="small"></el-input>
                </el-form-item>
                <el-form-item label="启用">
                    <el-switch
                            v-model="roleObj.roleDialog.status"
                            active-color="#13ce66"
                            inactive-color="#ff4949">
                    </el-switch>
                </el-form-item>
                <el-form-item label="菜单权限">
                    <el-tree
                            check-strictly
                            @check-change="handleEditCheckChange"
                            ref="editTree"
                            node-key="id"
                            :data="roleObj.menuTree"
                            :props="roleObj.props"
                            show-checkbox>
                    </el-tree>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="clearRoleDialog">取 消</el-button>
                <el-button type="primary" @click="updateRole('editRoleForm')">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="角色授权" :visible.sync="roleObj.dialogRoleUserVisible" width="50%">
            <el-row :gutter="20" class="form-line">
                <el-col :span="4" class="form-label">
                    人员名称
                </el-col>
                <el-col :span="4">
                    <el-input v-model="roleObj.roleUser.userName" size="small"></el-input>
                </el-col>
                <el-col :span="6" :offset="10">
                    <el-button type="primary" size="small" @click="selectRoleUser">查询</el-button>
                    <el-button type="primary" size="small" @click="roleObj.dialogRoleUserInsertVisible = true">新增</el-button>
                </el-col>
            </el-row>
            <el-table
                    :data="roleObj.roleUser.roleUserListShow"
                    min-width="100%">
                <el-table-column
                        prop="userId"
                        label="人员编号"
                        min-width="33%">
                </el-table-column>
                <el-table-column
                        prop="userName"
                        label="人员名称"
                        min-width="33%">
                </el-table-column>
                <el-table-column
                        label="操作" min-width="34%">
                    <template slot-scope="scope">
                        <el-popover
                                placement="top"
                                width="160"
                                v-model="scope.row.popover">
                            <p>确认删除？</p>
                            <div style="text-align: right; margin: 0">
                                <el-button size="mini" type="text" @click="scope.row.popover = false">取消</el-button>
                                <el-button type="primary" size="mini" @click="deleteRoleUser(scope.row.id)">确定</el-button>
                            </div>
                            <el-button class="delete-margin" size="small" type="text" slot="reference">删除</el-button>
                        </el-popover>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                    class="se-pagination"
                    @size-change="handleSizeChangeDialog"
                    @current-change="handleCurrentChangeDialog"
                    :current-page.sync="roleObj.roleUser.currentPage"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="roleObj.roleUser.currentSize"
                    :hide-on-single-page="false"
                    layout="total, sizes, prev, pager, next"
                    :total="roleObj.roleUser.total">
            </el-pagination>

            <el-dialog title="新增授权" :visible.sync="roleObj.dialogRoleUserInsertVisible" width="30%" append-to-body>
                <el-form  label-width="80px" :model="roleObj.roleUser.insertDialog" :rules="roleUserRules" ref="roleUserForm">
                    <el-form-item label="查询人员" prop="userId">
                        <el-select
                                size="small"
                                v-model="roleObj.roleUser.insertDialog.userId"
                                filterable
                                remote
                                reserve-keyword
                                placeholder="请输入编号或姓名"
                                :remote-method="selectUser"
                                :loading="roleObj.roleUser.insertDialog.loading">
                            <el-option
                                    v-for="item in roleObj.roleUser.insertDialog.userList"
                                    :key="item.userId"
                                    :label="item.userName"
                                    :value="item.userId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="roleObj.dialogRoleUserInsertVisible = false">取 消</el-button>
                    <el-button type="primary" @click="insertRoleUser('roleUserForm')">确 定</el-button>
                </div>
            </el-dialog>
        </el-dialog>
    </div>
</template>

<script>
    module.exports = {
        data() {
            return {
                roleObj: {
                    serviceCode: "",
                    serviceList: [],
                    roleList: [],
                    roleListShow: [],
                    roleName: "",
                    currentPage: 1,
                    currentSize: 10,
                    total: 0,
                    dialogFormVisible: false,
                    dialogEditRoleVisible: false,
                    dialogRoleUserVisible: false,
                    dialogRoleUserInsertVisible: false,
                    userId: "",
                    loading: false,
                    manager: false,
                    roleDialog: {
                        id: "",
                        roleName: "",
                        descr: "",
                        status: true
                    },
                    props: {
                        label: 'menuName',
                        children: 'childList'
                    },
                    menuTreePreViewCheck: false,
                    menuTree: [],
                    roleUser: {
                        roleId: "",
                        userName: "",
                        roleUserList: [],
                        roleUserListShow: [],
                        insertDialog: {
                            userId: "",
                            userName: "",
                            loading: false,
                            userList: []
                        },
                        currentPage: 1,
                        currentSize: 10,
                        total: 0
                    }
                },
                roleRules: {
                    roleName: [
                        {required: true, message: '请输入角色名称', trigger: 'change'}
                    ]
                },
                roleUserRules: {
                    userId: [
                        {required: true, message: '请选择人员', trigger: 'change'}
                    ]
                }
            };
        },
        mounted: function () {
            this.selectServiceList();
        },
        methods: {
            selectServiceList: function () {
                axios.get('/se/common/selectService'
                ).then(res => {//用function会获取不到vue data值
                    this.roleObj.serviceList = res.data.data;
                    if (this.roleObj.serviceList.length > 0) {
                        this.roleObj.serviceCode = this.roleObj.serviceList[0].serviceCode;
                        this.selectRoleList();
                        this.selectMenuTree();
                    }
                }).catch(function (error) {
                    console.log(error);
                });
            },
            changeService: function (val) {
                this.selectRoleList();
                this.selectMenuTree();
            },
            selectRoleList: function () {
                axios.get('/se/role/selectRolePage', {
                    params: {
                        serviceCode: this.roleObj.serviceCode,
                        roleName: this.roleObj.roleName
                    }
                }).then(res => {//用function会获取不到vue data值
                    this.roleObj.roleList = res.data.data;
                    this.roleObj.total = this.roleObj.roleList.length;
                    this.showCurrentPage();
                }).catch(function (error) {
                    console.log(error);
                });
            },
            handleSizeChange: function (pageSize) {
                this.roleObj.currentSize = pageSize;
                this.showCurrentPage();
            },
            handleCurrentChange: function (curPage) {
                this.showCurrentPage();
            },
            showCurrentPage: function () {
                let start = (this.roleObj.currentPage - 1) * this.roleObj.currentSize;
                let end = this.roleObj.currentPage * this.roleObj.currentSize;
                this.roleObj.roleListShow = this.roleObj.roleList.slice(start,end);
            },
            handleSizeChangeDialog: function (pageSize) {
                this.roleObj.roleUser.currentSize = pageSize;
                this.showCurrentPageDialog();
            },
            handleCurrentChangeDialog: function (curPage) {
                this.showCurrentPageDialog();
            },
            showCurrentPageDialog: function () {
                let start = (this.roleObj.roleUser.currentPage - 1) * this.roleObj.roleUser.currentSize;
                let end = this.roleObj.roleUser.currentPage * this.roleObj.roleUser.currentSize;
                this.roleObj.roleUser.roleUserListShow = this.roleObj.roleUser.roleUserList.slice(start,end);
            },
            insertRole: function (formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        axios.post('/se/role/insertRole',
                            Qs.stringify({
                                serviceCode: this.roleObj.serviceCode,
                                roleName: this.roleObj.roleDialog.roleName,
                                descr: this.roleObj.roleDialog.descr,
                                status: this.roleObj.roleDialog.status == true ? 1 : 0,
                                menuIds: this.$refs.insertTree.getCheckedKeys().join(",")
                            })
                        ).then(res => {
                            this.selectRoleList();
                            this.clearRoleDialog();
                            this.$refs.insertTree.setCheckedKeys([]);
                        });
                    } else {
                        return false;
                    }
                });

            },
            deleteRole: function (id) {
                axios.delete('/se/role/deleteRole',
                    {
                        params: {
                            id: id
                        }
                    }
                ).then(res => {
                    this.selectRoleList();
                });
            },
            updateRole: function (formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        axios.put('/se/role/updateRole',
                            Qs.stringify({
                                id: this.roleObj.roleDialog.id,
                                serviceCode: this.roleObj.serviceCode,
                                roleName: this.roleObj.roleDialog.roleName,
                                descr: this.roleObj.roleDialog.descr,
                                status: this.roleObj.roleDialog.status == true ? 1 : 0,
                                menuIds: this.$refs.editTree.getCheckedKeys().join(",")
                            })
                        ).then(res => {
                            this.selectRoleList();
                            this.clearRoleDialog();
                            this.$refs.editTree.setCheckedKeys([]);
                        });
                    } else {
                        return false;
                    }
                });
            },
            clearRoleDialog: function () {
                this.roleObj.roleDialog.id = null;
                this.roleObj.roleDialog.roleName = null;
                this.roleObj.roleDialog.descr = null;
                this.roleObj.roleDialog.status == true;
                this.roleObj.dialogFormVisible = false
                this.roleObj.dialogEditRoleVisible = false
            },
            selectMenuTree: function () {
                axios.get('/se/menu/selectMenuTree', {
                    params: {
                        serviceCode: this.roleObj.serviceCode,
                        includeApi: 1
                    }
                }).then(res => {
                    this.roleObj.menuTree = res.data.data;
                }).catch(function (error) {
                    console.log(error);
                });
            },
            openEditDialog: function (rowData) {
                this.roleObj.dialogEditRoleVisible = true;
                this.roleObj.roleDialog.id = rowData.id;
                this.roleObj.roleDialog.roleName = rowData.roleName;
                this.roleObj.roleDialog.descr = rowData.descr;
                this.roleObj.roleDialog.status = rowData.status == 1 ? true : false;
                this.roleObj.menuTreePreViewCheck = false;

                axios.get('/se/role/selectRoleMenu', {
                    params: {
                        id: rowData.id
                    }
                }).then(res => {//用function会获取不到vue data值

//                    setTimeout(() =>{
//                        res.data.data.forEach(value => {
//                            alert(value.id);
//                            this.$refs.editTree.setChecked(value.menuId, true, false);
//                        })}, 1000)

                    let roleMenuArrs = [];
                    res.data.data.forEach(function (item) {
                        roleMenuArrs.push(item.menuId);
                    });

                    this.$refs.editTree.setCheckedKeys(roleMenuArrs);
                    setTimeout(() =>{
                        this.roleObj.menuTreePreViewCheck = true;
                    }, 500);
                }).catch(function (error) {
                    console.log(error);
                });
            },
            openUserDialog: function (rowData) {
                this.roleObj.dialogRoleUserVisible = true;
                this.roleObj.roleUser.roleId = rowData.id;
                this.selectRoleUser();
            },
            selectRoleUser: function () {
                axios.get('/se/role/selectRoleUserList', {
                    params: {
                        roleId: this.roleObj.roleUser.roleId,
                        userName: this.roleObj.roleUser.userName
                    }
                }).then(res => {
                    this.roleObj.roleUser.roleUserList = res.data.data;
                    this.roleObj.roleUser.total = this.roleObj.roleUser.roleUserList.length;
                    this.showCurrentPageDialog();
                }).catch(function (error) {
                    console.log(error);
                });
            },
            deleteRoleUser: function (id) {
                axios.delete('/se/role/deleteRoleUser',
                    {
                        params: {
                            id: id
                        }
                    }
                ).then(res => {
                    this.selectRoleUser();
                });
            },
            selectUser: function (query) {
                if (query !== '') {
                    this.loading = true;
                    setTimeout(() => {
                        axios.get('/se/common/searchUser', {
                            params: {
                                userContent: query
                            }
                        }).then(res => {
                            this.roleObj.roleUser.insertDialog.userList = res.data.data;
                        }).catch(function (error) {
                            console.log(error);
                        });

                        this.loading = false;
                    }, 200);
                }
            },
            insertRoleUser: function (formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        axios.post('/se/role/insertRoleUser',
                            Qs.stringify({
                                serviceCode: this.roleObj.serviceCode,
                                roleId: this.roleObj.roleUser.roleId,
                                userId: this.roleObj.roleUser.insertDialog.userId,
                                userName: this.roleObj.roleUser.insertDialog.userList.filter(item => item.userId == this.roleObj.roleUser.insertDialog.userId)[0].userName
                            })
                        ).then(res => {
                            this.selectRoleUser();
                            this.roleObj.dialogRoleUserInsertVisible = false;
                        });
                    } else {
                        return false;
                    }
                });
            },
            handleInsertCheckChange(data, checked, indeterminate) {
                if (data.childList != null) {
                    data.childList.forEach(e =>{
                        this.$refs.insertTree.setChecked(e.id, checked, true);
                    });
                }
            },
            handleEditCheckChange(data, checked, indeterminate) {
                if (this.roleObj.menuTreePreViewCheck) {
                    if (data.childList != null) {
                        data.childList.forEach(e =>{
                            this.$refs.editTree.setChecked(e.id, checked, true);
                        });
                    }
                }
            },
            statusMenu: function (id,status) {
                axios.put('/se/role/statusRole',
                    Qs.stringify({
                        id: id,
                        status: status == true ? "1" : "0"
                    })
                ).then(res => {

                }).catch(function (error) {
                    console.log(error);
                });
            }
        },
        watch: {
            '$route' (to, from) {
                this.selectServiceList();
            }
        }
    }
</script>